package cn.jiyun.common;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class ReverseGeocodingService {

    @Value("${amap.key}")
    private String amapKey;

    public String getAddressByCoordinates(double latitude, double longitude) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=" + longitude + "," + latitude + "&key=" + amapKey;
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            String responseBody = response.getBody();
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                JsonNode rootNode = objectMapper.readTree(responseBody);
                JsonNode regeocodeNode = rootNode.path("regeocode");
                JsonNode formattedAddressNode = regeocodeNode.path("formatted_address");
                if (formattedAddressNode != null && !formattedAddressNode.isNull()) {
                    return formattedAddressNode.asText();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
